require('./db')
const Setting = require('./setting')
const express = require('express');
const cors = require('cors')
const deviceRouter = require('./routes/device')
const userRouter = require('./routes/user')
const reportRouter = require('./routes/report')
const warningRouter = require('./routes/warning')
const verToken = require('./token')
const expressJwt = require('express-jwt')
const app = express();
//配置Socket
const http = require('http').Server(app)
const io = require('socket.io')(http, {
  allowEIO3: true,
  cors: {
    origin: 'http://localhost',
    credentials: true
  }
})

io.on('connection',socket => {
  console.log(socket.id + ' connected')
  socket.on('disconnect', () => {
    console.log(socket.id + 'Disconnection')
  })
  socket.on(Setting.TestMessage, (msg) => {
    io.emit(Setting.TestMessage, msg)
    console.log(Setting.TestMessage, msg)
  })
})
//解析token获取用户信息
app.use(function(req, res, next) {
  let token = req.headers['authorization'];
  if(token === undefined){
    return next();
  }else{
    verToken.getToken(token).then((data)=> {
      req.data = data;
      return next();
    }).catch((error)=>{
      return next();
    })
  }
});
//验证token是否过期并规定那些路由不需要验证
app.use(expressJwt({
  secret:'LiKu_token',
  algorithms:['HS256']
}).unless({
  path:['/user/login']  //不需要验证的接口名称
}))
//token失效返回信息
app.use(function(err,req,res,next){
  if(err.status === 401){
    return res.status(401).send('token失效')
  }
})
//配置CORS跨域
app.use(cors())
//解析请求体的json和urlencoded格式
app.use(express.json())
app.use(express.urlencoded({ extended: false}))
//注册路由
app.use('/device',deviceRouter);
app.use('/user',userRouter);
app.use('/report',reportRouter);
app.use('/warning',warningRouter);
//定义端口号
http.listen(3000, function () {
  console.log('App listening on port 3000');
});
exports.emit = (data) => {
  io.emit(Setting.TestMessage, data)
}
